package com.lzy.crm.wechat.controller;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lzy.crm.base.date.DateUtil;
import com.lzy.crm.base.util.HttpUtil;
import com.lzy.crm.base.util.JsonUtil;
import com.lzy.crm.base.util.StringUtil;
import com.lzy.crm.domain.Mall;
import com.lzy.crm.domain.Order;
import com.lzy.crm.domain.PpUser;
import com.lzy.crm.domain.User;
import com.lzy.crm.proto.Group.CommMsg;
import com.lzy.crm.proto.Shop.shop_goods;
import com.lzy.crm.proto.Shop.shop_goods_list;
import com.lzy.crm.proto.Shop.shop_goods_list.Builder;
import com.lzy.crm.service.CardFlowService;
import com.lzy.crm.service.MallService;
import com.lzy.crm.service.OrderService;
import com.lzy.crm.service.UserService;
import com.lzy.crm.util.OrderConstants;
import com.lzy.crm.util.UserConstants;
import com.lzy.crm.vo.PlayerInfo;
import com.lzy.crm.wechat.consts.WechatPayProperties;
import com.lzy.crm.wechat.util.Sign;
import com.lzy.crm.wechat.util.WeixinUtil;
import com.lzy.crm.wechat.vo.AccessToken;
import com.lzy.crm.wechat.vo.WeChatHeader;
import com.lzy.crm.wechat.vo.WxPayDto;


/**
 * 订单控制器
 * @author chenshiping
 *
 */
@Controller
@RequestMapping("/gm")
public class GmMallController {
	
	Logger logger= Logger.getLogger(GmMallController.class);
	
	@Resource
	OrderService orderService; 
	
	@Resource
	UserService userService;
	
	@Resource
	CardFlowService cardFlowService;
	
	
	@Resource
	MallService mallService;
	/**
	 * 
	 * 游戏商城
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(path="/mall_list",method=RequestMethod.GET,produces="text/html;charset=UTF-8")  
	@ResponseBody
	public byte[] maiiList(HttpServletRequest request,ModelMap modelMap) {
		
		String uid = request.getParameter("uid");
		System.out.println(uid+"===================");
		com.lzy.crm.proto.Group.CommMsg.Builder commMsg = CommMsg.newBuilder();
		Builder list = shop_goods_list.newBuilder();
		// 设置后台邀请人数
		//modelMap.put("inviteNub", UserConstants.INVITE_NUB);
		//modelMap.put("agentMoney", UserConstants.BECOME_AGENT_MONEY);
		//PpUser user =(PpUser)request.getSession().getAttribute("userSession");
		if(!StringUtil.isEmpty(uid)){
			
		
		 List<Mall> mall = mallService.getMallList();
		 for (Mall m : mall) {
			System.out.println(mall.size());
			Integer id = m.getId();
			String mallName = m.getMallName().toString();
			System.out.println("商品名字：=======================================++++++++++++++++++"+mallName);
			String mallUrl = m.getMallUrl();
			System.out.println("路径名字：=======================================++++++++++++++++++"+mallUrl);
			String mallDescribe = m.getMallDescribe();
			Double mallPrice = (double)m.getMallPrice();
			String mallPriceDesc = m.getMallPriceDesc();
			Integer mallNub = m.getMallNub();
			String mallNubDesc = m.getMallNubDesc();
			Integer mallOrder = m.getMallOrder();
		
	
		
			shop_goods.Builder goods = shop_goods.newBuilder();
			
			goods.setItemId(id);
			goods.setName(mallName);
			goods.setUrl(mallUrl);
			goods.setDesc(mallDescribe);
			goods.setPrice(100);
			goods.setPriceDesc(mallPriceDesc);
			goods.setCount(mallNub);
			goods.setCountDesc(mallNubDesc);
			goods.setGoodsOrder(mallOrder);
			list.addGoodsList(goods);
		 }
		}
		/*if(StringUtil.equals(user.getUserType(), UserConstants.USER_TYPE_AGENT)||
				StringUtil.equals(user.getUserType(), UserConstants.USER_TYPE_MANAGE)){
			return "wechat/mall/mall_list_agent";  
		}*/
		commMsg.setCode(1);
		commMsg.setResp(list.build().toByteString()); 
		return commMsg.build().toByteArray(); 
	}
	
	
	
	/**
	 * 定价：8张   9.6元     
			18张  21.6元
			30张  36元
			60张  66元（省6元）
			100张 110元（省10元）
			288张 316.8元（省28.8元）
	 */
	/**
	 * 
	 * 公众号发起
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("order_pay")  
	public String orderPay(HttpServletRequest request,ModelMap modelMap) {
		boolean isAgent =false ;
		PpUser user =(PpUser)request.getSession().getAttribute("userSession");
		// 订单信息(订单标识)
		String maillId = request.getParameter("maillId");
		
		// 验证会话
		/*if(user==null||StringUtil.isEmpty(user.getOpenid())
				||StringUtil.isEmpty(user.getUnionid())
				){
			// 不构成支付条件
			modelMap.put("appid", WechatPayProperties.getAppId());
			modelMap.put("redirectUri", WechatPayProperties.getRedirectUri()+"?page=wechat/order_pay.html?maillId="+maillId);
			return "wechat/index2"; 
		}*/
		//查出了所需要的商品信息
		Mall mall = mallService.getMallById(maillId);
		//商品名称
		String mallName =  mall.getMallName();
		//常规商品价格
		Double money = (double)mall.getMallPrice();
		System.out.println("正常价格++++++++++++++++++++++++++++++++++："+money);
		//辅助商品价格
		//String mallPriceDesc = mall.getMallPriceDesc();
		//常规商品数量
		Integer carNub = mall.getMallNub();
		//辅助商品数量
		//String mallNubDesc = mall.getMallNubDesc();
		
		/*if(carNub==0|| money<0.1 ){
			modelMap.put("msg", "参数错误，请稍后再试 ~~");
			// 游戏下载页面
			return "wechat/game_list";
		}*/
		
		// 微信支付初始化
		WeChatHeader header = new WeChatHeader();
		// 订单信息
		
		/*if(user==null||StringUtil.isEmpty(user.getOpenid())
				||StringUtil.isEmpty(user.getUnionid())
				){
			// 不构成支付条件
			modelMap.put("appid", WechatPayProperties.getAppId());
			modelMap.put("redirectUri", WechatPayProperties.getRedirectUri()+"?page=wechat/order_pay.html?maillId="+maillId);
			return "wechat/game_list"; 
		}*/
		header.setOpenId(user.getOpenid());
		
		Order order =new Order();
		try {
			final AccessToken accessToken = WeixinUtil.getAccessToken(WechatPayProperties.getAppId() , WechatPayProperties.getAppSecret());
			// 获取路径
			String requestURL = request.getRequestURL().toString();
			String queryString = request.getQueryString(); // d=789
			if (queryString != null) {
				requestURL += "?" + queryString;
			}
			// 获取ip地址
			String ip = HttpUtil.getIpAddress(request);
			
			// 判断是否微信环境, 5.0 之后的支持微信支付
			//boolean isweixin = WeixinUtil.isWeiXin(request);
				//if (isweixin) {
					// 微信商品订单 
					//String productName =new String( merchantReq.getPobindVo().getCommodityName().getBytes(), "UTF-8") ;
					//商品名称
					//String productName = maillId ;
					//productName=   new String(productName.getBytes(), "ISO-8859-1") ;
					//支付金额
					String total_fee   = String.valueOf(money);// merchantReq.getPobindVo().getTotal_amount().toString();
					
					// 非推广大使 统计零售价
					/*if(!StringUtil.equals(user.getUserLevel(), UserConstants.USER_LEVEL_TGDS)){
						//代理商打折购买
						DecimalFormat    df   = new DecimalFormat("######0.00");   
						total_fee   = String.valueOf(df.format(carNub*Double.parseDouble(WechatPayProperties.getAgentPay())));
						
						// 显示代理优惠
						isAgent =true;
						
					}else{
						total_fee   = String.valueOf(money);
					}*/
					//订单好
					String orderId  = WeixinUtil.getTimeStamp()+ WeixinUtil.getNonceStr(); ; 
					 
					WxPayDto tpWxPay = new WxPayDto();
					tpWxPay.setOpenId(user.getOpenid());
					//tpWxPay.setBody(productName);
					tpWxPay.setOrderId(orderId);
					tpWxPay.setSpbillCreateIp(ip);
					tpWxPay.setTotalFee(total_fee);
					Map<String, String> finalpackage =WeixinUtil.getPackage(tpWxPay);
					String  jsapiTicket=WeixinUtil.getJsapiTicket(accessToken.getToken());
					// 生成微信apijs 参数
					Map<String,String> map = Sign.sign(jsapiTicket, requestURL,finalpackage.get("nonceStr"),finalpackage.get("timeStamp"));
					// timeStamp
					header.setTimeStamp( finalpackage.get("timeStamp"));
					// nonceStr
					header.setNonceStr( finalpackage.get("nonceStr") );
					// package
					header.setPackagestring(finalpackage.get("package") );
					// paySign
					header.setPaySign( finalpackage.get("paySign") ); //finalpackage.get("finaPackage"));//
					// 判定微信
					header.setSignType( finalpackage.get("signType"));
					header.setSignature(map.get("signature"));
					
					// 创建订单
					order.setMallId(Integer.parseInt(maillId));
					order.setMallName(mallName);
					order.setOrId(orderId);
					order.setOrNub(carNub);
					order.setOrPrive(1d);
					order.setOrMoney(Double.parseDouble(total_fee.toString()));
					order.setRemark("微信支付");
					order.setCreateTime(new Date());
					order.setStatus("0");
					order.setGameId(user.getUid());
					order.setUnionid(user.getUnionid());
					order.setOpenid(user.getOpenid());
					orderService.insertSelective(order);
				/*} else {
					modelMap.put("Msg", "请升级微信5.0 以上版本");
				}*/
			
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		String dayFormatNo =DateUtil.formatDate(new Date(), DateUtil.DAY_FORMAT_NO);
		/*// appID
		modelMap.put("appid", WechatPayProperties.getAppId());
		// timeStamp
		modelMap.put("timeStamp", header.getTimeStamp());
		// nonceStr
		modelMap.put("nonceStr", header.getNonceStr() );
		// package
		modelMap.put("packagestring",header.getPackagestring() );
		// paySign
		modelMap.put("paySign",  header.getPaySign() ); //finalpackage.get("finaPackage"));//
		// 判定微信
		modelMap.put("signType", header.getSignType());
		modelMap.put("signature", header.getSignature());
		modelMap.put("weChatHeader", header);
		order.setOrId(dayFormatNo+order.getOrId());
		modelMap.put("order", order);
		modelMap.put("isAgent", isAgent);
		System.out.println( JsonUtil.toJson(modelMap));*/
		return "wechat/mall/mall_pay";
	}
	
	
	
	
	
	/**
	 * 微信支付完成页面
	 * @param request
	 * @param orderNo
	 * @return
	 */
	@RequestMapping("pay_complete") 
	public String payComplete(HttpServletRequest request,ModelMap  modelMap ) {
		return "wechat/mall/pay_complete";
	}
	
	
	/**
	 * 微信支付回调接口
	 * @param request
	 * @param orderNo
	 * @return
	 */
	//@ResponseBody
	@RequestMapping("payResult/{orderNo}") 
	public String payResult(HttpServletRequest request, @PathVariable("orderNo")String orderNo) {
		//Map<String,String[]> map= request.getParameterMap();
		System.out.println("支付订单：orderNo:"+orderNo );
		logger.info("订单ID :"+orderNo);
		try {
			if(orderNo!=null){
				// 处理支付结构
				Order order =orderService.getOrderByorId(orderNo);
				if(StringUtil.equals(order.getStatus(),OrderConstants.ORDER_STATUS_INIT)){
					//处理加房卡
					cardFlowService.buyCardByWechat(order);
				}else if(StringUtil.equals(order.getStatus(), OrderConstants.ORDER_STATUS_SUCCEED)){
					logger.info(" 支付订单已处理：" +orderNo);
				}else{
					logger.info("支付失败");
				}
			}else{
				logger.info("参数错误");
			}
		} catch (Exception e) {
			logger.error("支付回调出错 orderNo:"+orderNo,e);
		}
		return "";
	}
	
	
}
